import { validNumberFromGet } from "../functionFromexport.js";

const WebApp = window.Telegram.WebApp;

const amountBalanceButton = document.querySelector(".btn");
// const amountCancelButton = document.querySelector(".button");
const closeBalanceWindow = document.getElementById("referrer");

const closePopoUp = document.getElementById("firstReferrer");

const radioEuro = document.getElementById("typeEuro");
const radioRuble = document.getElementById("typeRub");
const sendPayment = document.getElementById("sendPayment");
const amountInput = document.getElementById("summ");
const bonusInput = document.getElementById("bonusInput");

const howGetButton = document.getElementById("howGetLink");

let clientPhone = localStorage.getItem("phoneNumber");

clientPhone = validNumberFromGet(clientPhone);

// console.log(bonusInput);
// console.log(amountInput);
// console.log(sendPayment);

let startingIndex = 0;
let endingIndex = 10;
let clientDataArr = [];

const innerHistory = document.getElementById("innerHistory");

// let clientGroupId = getCookie("clientGroupId");
let clientGroupId = localStorage.getItem("clientGroupId");
console.log("local", clientGroupId);
WebApp.BackButton.hide();

// const urlRecords = `https://crm.caremybaby.ru/Remotes/tgwa_pc_get_records_QwhY655?client_group_id=${clientGroupId}`;
const showMoreButton = document.querySelector(".loadMore");

const closeBalanceWindowButton = document.getElementById("closeBtn1");
const closePopoUpButton = document.getElementById("closeBtn2");
const closePopoDownButton = document.getElementById("closePopUpButton");

amountBalanceButton.addEventListener("click", (e) => {
  e.preventDefault();
  document.getElementById("referrer").style.display = "flex";
});

howGetButton.addEventListener("click", () => {
  closePopoUp.style.display = "flex";
});

closePopoUpButton.addEventListener("click", () => {
  closePopoUp.style.display = "none";
});

closePopoUp.addEventListener("click", (e) => {
  if (e.target.id === "firstReferrer") {
    closePopoUp.style.display = "none";
  }
});

closePopoDownButton.addEventListener("click", () => {
  closePopoUp.style.display = "none";
});

// amountCancelButton.addEventListener("click", (e) => {
//   e.preventDefault();
//   document.getElementById("referrer").style.display = "none";
// });

closeBalanceWindowButton.addEventListener("click", () => {
  closeBalanceWindow.style.display = "none";
});

closeBalanceWindow.addEventListener("click", (e) => {
  if (e.target.id === "referrer") {
    closeBalanceWindow.style.display = "none";
  }
});

const innerErrMessage = document.getElementById("errMess");

amountInput.addEventListener("focus", () => {
  innerErrMessage.innerText = "";
  amountInput.style.border = "none";
});

let jsonClientObj = {};

setTimeout(() => {
  fetch("/client", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      clientPhone: clientPhone,
    }),
  })
    .then((response) => response.json())
    .then((data) => {
      console.log("получил", data);
      // displayClienName(data);
      jsonClientObj = data;
    })
    .catch((err) => {
      console.log(err);
    });
}, 600);

sendPayment.addEventListener("click", (e) => {
  e.preventDefault();
  if (amountInput.value.length > 0 && amountInput.value != 0) {
    if (radioRuble.checked) {
      // window.location.replace("https://ya.ru");
      // Telegram.WebApp.openLink("https://ya.ru");
      sendAmount();
    } else if (radioEuro.checked) {
      // window.location.replace(
      //   "https://www.google.ru/?gfe_rd=cr&ei=FXVQVdXGD46CYIbDgNAO"
      // );
      Telegram.WebApp.openLink(
        "https://www.google.ru/?gfe_rd=cr&ei=FXVQVdXGD46CYIbDgNAO"
      );
    }
  } else {
    innerErrMessage.innerText = "Введите корректную сумму";
    amountInput.style.border = "1px solid red";
    // alert("Введите сумму");
  }
});

const sendAmount = () => {
  // let testtest =
  //   "https://moneta.ru/assistant.widget?MNT_ID=93723251&MNT_AMOUNT=1&version=v3";
  // Telegram.WebApp.openLink(testtest);
  let date = new Date();
  let randNumber = Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000;
  let cT = `${date.getDate()}${date.getHours()}${date.getMinutes()}${date.getSeconds()}${randNumber}`;

  fetch("/api/amount", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      MNT_AMOUNT: amountInput.value,
      bonus: bonusInput.value,
      MNT_TRANSACTION_ID: cT,
      client: jsonClientObj,
    }),
  })
    .then((res) => res.json())
    .then((data) => {
      console.log(data);
      setTimeout(() => {
        window.location.replace(
          `https://moneta.ru/assistant.widget?operationId=${data}`
        );
        // Telegram.WebApp.openLink(
        //   `https://moneta.ru/assistant.widget?operationId=${data}`
        // );
      }, 1000);
    })
    .catch((err) => {
      console.log(err);
    });
};

fetch("/getrecords", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    clientGroupId: clientGroupId,
  }),
})
  .then((res) => res.json())
  .then((data) => {
    clientDataArr = data;
    console.log(clientDataArr);
    if (clientDataArr.length >= 10) {
      showMoreButton.classList.remove("classHide");
    }
    if (showMoreButton.classList[1] == "classHide") {
      innerHistory.style.marginBottom = "50px";
    }
    displayHistory(clientDataArr.slice(startingIndex, endingIndex));
  })
  .catch((err) => {
    console.log(err);
  });

const displayHistory = (client) => {
  client.forEach(
    (
      { lesson_date, client_valute, cost_sale, amount, type_id, is_bonus },
      index
    ) => {
      let icon = "₽";
      let degree = "+";
      let message = "Пополнение счета";
      let innerSpan = `<p class="historyDate">${lesson_date}</p>`;
      if (client_valute === "евро") {
        icon = "€";
      }
      if (is_bonus) {
        message = "Бонусы";
      }
      if (type_id != 10) {
        degree = "-";
        message = "Платная отмена";
      }

      if (amount != undefined) {
        // if (type_id == 10){}
        innerHistory.innerHTML += `
        <div class="history">
        ${innerSpan}
        <div class="operation">
          <p>${message}</p>
          <p class="amount">${degree} ${amount} ${icon}</p>
        </div>`;
      } else {
        innerHistory.innerHTML += `
      <div class="history">
      ${innerSpan}
      <div class="operation">
        <p>Оплата за урок</p>
        <p class="amount">- ${cost_sale} ${icon}</p>
      </div>`;
      }
    }
  );
  checkDateLesson();
}; // нужна ли обработка нулевых занятий?

const checkDateLesson = () => {
  const allHistory = document.querySelectorAll(".history");
  const allLesDay = document.querySelectorAll(".historyDate");
  // console.log(allLesDay);
  for (let i = 0; i < allHistory.length; i++) {
    // console.log(allLesDay[i].innerText);
    if (allLesDay[i + 1] != undefined) {
      if (allLesDay[i].innerText == allLesDay[i + 1].innerText) {
        allLesDay[i + 1].classList.add("classHide");
        allHistory[i].classList.add("removeMargin");
      }
    }
  }
};

const fetchMoreClient = () => {
  startingIndex += 10;
  endingIndex += 10;
  displayHistory(clientDataArr.slice(startingIndex, endingIndex));
  if (clientDataArr.length <= endingIndex) {
    showMoreButton.classList.add("classHide");
    innerHistory.style.marginBottom = "50px";
  }
};

showMoreButton.addEventListener("click", fetchMoreClient);
